﻿using System;
using System.Collections.Generic;

namespace NiuX.Collections;

public class ValueChangedEventArgs<TKey> : EventArgs
{
    public TKey Key { get; set; }

    public ValueChangedEventArgs(TKey key)
    {
        Key = key;
    }
}

public class DictionaryWapper<TKey, TValue> where TKey : notnull
{
    private readonly object _locker = new();

    private readonly Dictionary<TKey, TValue> _dict;

    public event EventHandler<ValueChangedEventArgs<TKey>> OnValueChanged;

    public DictionaryWapper(Dictionary<TKey, TValue> dict)
    {
        _dict = dict;
    }

    public TValue this[TKey Key]
    {
        get => _dict[Key];
        set
        {
            lock (_locker)
            {
                try
                {
                    if (_dict.ContainsKey(Key) && _dict[Key] != null && !_dict[Key].Equals(value))
                    {
                        OnValueChanged(this, new ValueChangedEventArgs<TKey>(Key));
                    }
                }
                catch (Exception ex)
                {
                    // Console.WriteLine($"检测值变更或者触发值变更事件，发生未知异常{ex}");
                }
                finally
                {
                    _dict[Key] = value;
                }
            }
        }
    }
}